package com.huihui.adapter;

import android.app.Activity;
import android.content.Context;
import android.graphics.drawable.ColorDrawable;
import android.media.MediaPlayer;
import android.net.Uri;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.huihui.R;
import com.huihui.base.BaseActivity;
import com.huihui.bean.Comment;
import com.huihui.bean.SmallVideo;
import com.huihui.datamanager.AppManager;
import com.huihui.network.HttpContants;
import com.huihui.network.OkHttpRequest;
import com.huihui.network.base.CallBackUtil;
import com.huihui.utils.LoadImageUtil;
import com.huihui.utils.ShareUtils;
import com.huihui.utils.ToolUtils;
import com.huihui.widget.FullScreenVideoView;
import com.huihui.widget.ResizableImageView;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import de.hdodenhof.circleimageview.CircleImageView;
import okhttp3.Call;

/**
 * 抖音适配器
 */

public class DouyinAdapter extends RecyclerView.Adapter<DouyinAdapter.ViewHolder> {

    private Context mContext;
    private List<SmallVideo> list;
    private Map<Integer,FullScreenVideoView> videoViewMap =new HashMap<>();
    public DouyinAdapter(Context context, List<SmallVideo> list) {
        mContext = context;
        this.list = list;
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_view_pager, parent, false);
        return new ViewHolder(view);
    }

    @Override
    public void onDetachedFromRecyclerView(RecyclerView recyclerView) {
        super.onDetachedFromRecyclerView(recyclerView);
    }

    @Override
    public void onViewDetachedFromWindow(ViewHolder holder) {
        holder.play.setVisibility(View.VISIBLE);
        holder.img_thumb.setVisibility(View.VISIBLE);
        holder.video_view.stopPlayback();
    }

    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {
        SmallVideo smallVideo = list.get(position);
        if (smallVideo != null) {
            LoadImageUtil.displayImage(mContext, smallVideo.getUser_head_photo(), holder.user_head);
            holder.user_name.setText(smallVideo.getUser_nick_name());
            LoadImageUtil.displayImagePreview(mContext, smallVideo.getThumbnail_url(), holder.img_thumb, R.color.color_e9e9e9, false);
            holder.share_num.setText(String.valueOf(smallVideo.getShare_num()));
            holder.comment_num.setText(String.valueOf(smallVideo.getComment_num()));
            holder.zan_num.setText(String.valueOf(smallVideo.getCollection_num()));
            holder.video_content.setText(smallVideo.getVideo_title());
            holder.video_view.setVideoURI(Uri.parse(smallVideo.getVideo_link()));
            if (smallVideo.getIs_like() == 1) {
                holder.zan.setImageResource(R.mipmap.zan_video_press);
            } else {
                holder.zan.setImageResource(R.mipmap.zan_video);
            }
            videoViewMap.clear();
            videoViewMap.put(position,holder.video_view);
            initListener(holder, position);
        }
    }
    public void stopVideView(int position){
        if(videoViewMap.containsKey(position)){
            FullScreenVideoView fullScreenVideoView = videoViewMap.get(position);
            if(fullScreenVideoView.isPlaying()){
                fullScreenVideoView.pause();
                Log.d("SmallVideoFragment","stopVideView success");
            }
        }
    }
    private void initListener(final ViewHolder holder, final int position) {
        holder.zan.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (list.get(position).getIs_like() == 0) {
                    //点赞
                    OkHttpRequest.getInstance().addCollection(HttpContants.addCollection, AppManager.getUserInfo().getUser_id(), list.get(position).getVideo_id(), 1, 0, new CallBackUtil.CallBackString() {
                        @Override
                        public void onFailure(Call call, Exception e) {

                        }

                        @Override
                        public void onResponse(String response) {
                            try {
                                JSONObject json = new JSONObject(response);
                                if (json != null && json.has(HttpContants.STATE) && json.getInt(HttpContants.STATE) == 10000) {
                                    list.get(position).setIs_like(1);
                                    list.get(position).setCollection_num(list.get(position).getCollection_num() + 1);
                                    notifyDataSetChanged();
                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }
                    });
                } else {
                    //取消点赞
                    removeZan(position);
                }
            }
        });

        holder.comment.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //评论
            }
        });

        holder.share.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //分享
                showSharePop(v, position);
            }
        });


        holder.video_view.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {
                holder.play.setVisibility(View.VISIBLE);
                holder.img_thumb.setVisibility(View.VISIBLE);
            }
        });


        holder.video_view.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //播放或者暂停
                if (holder.play.getVisibility() == View.VISIBLE) {
                    holder.play.setVisibility(View.INVISIBLE);
                    holder.video_view.start();
                    holder.video_view.requestFocus();
                    holder.img_thumb.setVisibility(View.GONE);
                } else {
                    holder.play.setVisibility(View.VISIBLE);
                    holder.video_view.pause();
                }

            }
        });

        holder.img_thumb.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //播放或者暂停
                if (holder.play.getVisibility() == View.VISIBLE) {
                    holder.play.setVisibility(View.INVISIBLE);
                    holder.video_view.start();
                    holder.video_view.requestFocus();
                    holder.img_thumb.setVisibility(View.GONE);
                } else {
                    holder.play.setVisibility(View.VISIBLE);
                    holder.video_view.pause();
                }

            }
        });
        holder.video_view.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
            @Override
            public void onPrepared(MediaPlayer mp) {
                mp.setOnVideoSizeChangedListener(new MediaPlayer.OnVideoSizeChangedListener() {
                    @Override
                    public void onVideoSizeChanged(MediaPlayer mp, int width, int height) {
                        mVideoWidth = mp.getVideoWidth();
                        mVideoHeight = mp.getVideoHeight();
                        showVideoHeight = holder.video_view.getHeight();
                        showViewWidth = holder.video_view.getWidth();
                        scaleHeight = (float)mVideoHeight / (float)showVideoHeight;
                        scaleWidth = (float)mVideoWidth / (float)showViewWidth;
                        if (scaleWidth > scaleHeight) {
                            scale = scaleWidth;

                        }else {
                            scale = scaleHeight;
                        }
                        scale = scaleWidth;

//                        scale = (float) mVideoWidth / (float) mVideoHeight;
                        refreshPortraitScreen(holder.video_view, showVideoHeight == 0 ? ToolUtils.dp2px(mContext, 300) : showVideoHeight
                        ,showViewWidth == 0 ? ToolUtils.dp2px(mContext, 300) : showViewWidth);
                    }
                });
            }
        });
        if (pingLunListener != null) {
            holder.comment.setTag(position);
            holder.comment.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    int p = (int) v.getTag();
                    pingLunListener.onCLick(p);
                }
            });
        }
    }


    private void showSharePop(View layout, final int position) {
        View view = LayoutInflater.from(mContext).inflate(R.layout.pop_share_layout, null);
        final PopupWindow pop = new PopupWindow(view, WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.WRAP_CONTENT, true);
        pop.setOutsideTouchable(true);
        pop.setFocusable(true);
        pop.setBackgroundDrawable(new ColorDrawable());
        pop.showAtLocation(layout, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
        backgroundAlpha(0.5f);
        pop.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                backgroundAlpha(1f);
            }
        });
        view.findViewById(R.id.wechat_friend).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                send(pop, position, 0);
            }
        });

        view.findViewById(R.id.wechat_cicle).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                send(pop, position, 1);
            }
        });
        view.findViewById(R.id.pop_cancel).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                pop.dismiss();
            }
        });
    }

    /**
     * 设置添加屏幕的背景透明度
     *
     * @param bgAlpha
     */
    public void backgroundAlpha(float bgAlpha) {
        WindowManager.LayoutParams lp = ((BaseActivity) mContext).getWindow().getAttributes();
        lp.alpha = bgAlpha; //0.0-1.0
        ((BaseActivity) mContext).getWindow().setAttributes(lp);
        ((BaseActivity) mContext).getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
    }


    private void send(final PopupWindow pop, final int position, final int type) {
        pop.dismiss();
        //获取链接
        OkHttpRequest.getInstance().getShareUrl(HttpContants.SHARE_URL, AppManager.getUserInfo().getUser_id(), 1, list.get(position).getVideo_id(), new CallBackUtil.CallBackString() {
            @Override
            public void onFailure(Call call, Exception e) {

            }

            @Override
            public void onResponse(String response) {
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    if (jsonObject != null) {
                        String url = jsonObject.getString("url");
                        ShareUtils.shareSelect((Activity) mContext, url, type, list.get(position).getVideo_title(), "信息来自视频," + list.get(position).getUser_nick_name());
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }
        });
    }

    public interface onPingLunListener {
        void onCLick(int position);
    }

    private onPingLunListener pingLunListener;

    public void setOnPingLunListener(onPingLunListener listener) {
        this.pingLunListener = listener;
    }

    @Override
    public int getItemCount() {
        return list == null ? 0 : list.size();
    }


    class ViewHolder extends RecyclerView.ViewHolder {
        private CircleImageView user_head;
        private ImageView zan;
        private ImageView comment;
        private ImageView share;
        private TextView video_content;
        private TextView user_name;
        private ImageView play;
        private FullScreenVideoView video_view;
        private ResizableImageView img_thumb;
        private TextView zan_num;
        private TextView comment_num;
        private TextView share_num;
        private LinearLayout comment_rl;

        public ViewHolder(View itemView) {
            super(itemView);
            user_head = itemView.findViewById(R.id.user_head);
            zan = itemView.findViewById(R.id.zan);
            comment = itemView.findViewById(R.id.comment);
            share = itemView.findViewById(R.id.share);
            video_content = itemView.findViewById(R.id.video_content);
            user_name = itemView.findViewById(R.id.user_name);
            play = itemView.findViewById(R.id.play);
            video_view = itemView.findViewById(R.id.video_view);
            img_thumb = itemView.findViewById(R.id.img_thumb);
            zan_num = itemView.findViewById(R.id.zan_num);
            comment_num = itemView.findViewById(R.id.comment_num);
            share_num = itemView.findViewById(R.id.share_num);
            comment_rl = itemView.findViewById(R.id.comment_rl);
        }
    }

    private void removeZan(int p) {
        int class_id = 1;
        final SmallVideo smallVideo = list.get(p);
        long video_id = smallVideo.getVideo_id();
        int coment_id = 0;
        OkHttpRequest.getInstance().removeCollection(HttpContants.removeCollection, AppManager.getUserInfo().getUser_id(),
                video_id, class_id, coment_id, new CallBackUtil.CallBackString() {
                    @Override
                    public void onFailure(Call call, Exception e) {

                    }

                    @Override
                    public void onResponse(String response) {
                        try {
                            JSONObject productObject = new JSONObject(response);
                            if (productObject != null && productObject.has(HttpContants.STATE) && productObject.getInt(HttpContants.STATE) == 10000) {
                                smallVideo.setCollection_num(smallVideo.getCollection_num() - 1);
                                smallVideo.setIs_like(0);
                                notifyDataSetChanged();
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                });
    }

    int showVideoHeight = 0;
    int showViewWidth = 0;
    int mVideoHeight = 0;
    int mVideoWidth = 0;
    float scale = 0;
    float scaleWidth = 0;
    float scaleHeight = 0;

    //重新刷新 竖屏显示的大小  树屏显示以宽度为准
    public void refreshPortraitScreen(FullScreenVideoView mVideoView, int height,int width) {
        if (height == 0) {
            height = showVideoHeight;
        }
        if (mVideoHeight > 0 && mVideoWidth > 0) {

            mVideoWidth = (int) (mVideoWidth / scale);
            mVideoHeight = (int) (mVideoHeight / scale);
            mVideoView.getHolder().setFixedSize(mVideoWidth, mVideoHeight);
            mVideoView.setMeasure(mVideoWidth, mVideoHeight);
            mVideoView.requestLayout();
        }
    }
}
